package net.sourceforge.krama.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import net.sourceforge.krama.introspection.TIntrospection;
import net.sourceforge.krama.introspection.TMethod;
import net.sourceforge.krama.xml.TXMLLoader;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionMapping;
import org.jdom.Document;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class TAjaxServlet extends HttpServlet {

	private String configKrama;
	private ServletConfig config;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		
		this.config = config;
		configKrama = config.getServletContext().getInitParameter("configKrama");
		configKrama = config.getServletContext().getRealPath(configKrama);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		String classe = request.getParameter("cName");
		String methode = request.getParameter("mName");
		int paramNumber = Integer.parseInt(request.getParameter("nParam")
				.toString());
		Object[] paramValue = new Object[paramNumber];
		
		for (int i = 0; i < paramNumber; i++) {
			String param = request.getParameter("param" + ((int) i + 1))
					.toString();
			if (param.equals("null"))
				paramValue[i] = null;
			else if (param.equals("true") || param.equals("false"))
				paramValue[i] = (Object) Boolean.parseBoolean(param);
			else if (param.matches("\\p{Digit}+")) {
				paramValue[i] = (Object) Integer.parseInt(param);
			} else
				paramValue[i] = (Object) param;
		}

		TXMLLoader kramaInstance = TXMLLoader.getInstance();
		Document document = kramaInstance.openkramaConfig(configKrama);
		TMethod tMethod = kramaInstance.parsingkramaConfigMethod(document, classe,
				methode, paramValue);
		Object result = TIntrospection.getResult(tMethod, paramValue);
		
		String key = kramaInstance.parsingkramaConfigJSPKey(document);
		String pageName = kramaInstance.parsingkramaConfigJSPPageName(document);
		request.getSession().setAttribute(key, result);
		request.getRequestDispatcher(pageName).forward(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}
}
